﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using BLL;
using System.Threading;
using DAL;

namespace MachineDemo
{
    public partial class FormMain : Form
    {
        ConnectionSetForm _FormConnSet;
        ConnTestForm _ConnTestForm;
        OrderForm _OrderForm ;
        Logic _LogicClass;

        CancellationTokenSource ScanConnDevice= new CancellationTokenSource();
        public FormMain()
        {
            InitializeComponent();
            #region 事件绑定
            LogSingle.Instaince.WriteMainLogThing = AddLog;//Log信息栏
            LogSingle.Instaince.WriteOrderStateThing += OrderState;//订单窗口状态
            #endregion
            _LogicClass = LogicSingle.Instaince;

            GetAllInitInfo(this.Controls[0]);//自适应

            LogSingle.Instaince.WriteOrderState(LogicSingle.Instaince._LocalWorkingMessage.State);
            //OrderState(LogicSingle.Instaince._LocalWorkingMessage.State);


            _FormConnSet = new ConnectionSetForm();
            _ConnTestForm = new ConnTestForm();
             _OrderForm = new OrderForm();
            Openpanel(_OrderForm, panel_Right);//打开订单窗口
            FormNow = _OrderForm;//设置要缩放窗口对象
            StateThread();//设备状态线程
        }

        #region 无边框窗体拖拽
        //窗体移动
        private Point MouseP;
        private bool MouseDown = false;
        #region 鼠标按下

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            if (!MouseDown)
            {
                MouseDown = true;
                MouseP = new Point(-e.X, -e.Y);


            }
        }
        #endregion

        #region 鼠标弹起

        private void label1_MouseUp(object sender, MouseEventArgs e)
        {
            if (MouseDown)
            {
                MouseDown = false;
            }
        }

        #endregion

        #region 鼠标移动
        private void label1_MouseMove(object sender, MouseEventArgs e)
        {
            if (MouseDown)
            {
                Point Mouse = Control.MousePosition;
                Mouse.Offset(MouseP);
                this.Location = Mouse;
            }
        }
        #endregion
        #endregion

        #region 自适应
        #region 控件缩放
        double formWidth;//窗体原始宽度
        double formHeight;//窗体原始高度
        double scaleX;//水平缩放比例
        double scaleY;//垂直缩放比例
        Dictionary<string, string> ControlsInfo = new Dictionary<string, string>();//控件中心Left,Top,控件Width,控件Height,控件字体Size

        private void frmMain_SizeChanged(object sender, EventArgs e)
        {

        }
        protected void GetAllInitInfo(Control ctrlContainer)
        {
            if (ctrlContainer.Parent == this)//获取窗体的高度和宽度
            {
                formWidth = Convert.ToDouble(ctrlContainer.Width);
                formHeight = Convert.ToDouble(ctrlContainer.Height);
            }
            foreach (Control item in ctrlContainer.Controls)
            {
                if (item.Name.Trim() != "")
                {
                    //添加信息：键值：控件名，内容：据左边距离，距顶部距离，控件宽度，控件高度，控件字体。
                    ControlsInfo.Add(item.Name, (item.Left + item.Width / 2) + "," + (item.Top + item.Height / 2) + "," + item.Width + "," + item.Height + "," + item.Font.Size);
                }
                if ((item as UserControl) == null && item.Controls.Count > 0)
                {
                    GetAllInitInfo(item);
                }
            }
        }

        private void ControlsChaneInit(Control ctrlContainer)
        {
            scaleX = (Convert.ToDouble(ctrlContainer.Width) / formWidth);
            scaleY = (Convert.ToDouble(ctrlContainer.Height) / formHeight);
        }
        /// <summary>
        /// 改变控件大小
        /// </summary>
        /// <param name="ctrlContainer"></param>
        private void ControlsChange(Control ctrlContainer)
        {
            double[] pos = new double[5];//pos数组保存当前控件中心Left,Top,控件Width,控件Height,控件字体Size
            foreach (Control item in ctrlContainer.Controls)//遍历控件
            {
                if (item.Name.Trim() != "")//如果控件名不是空，则执行
                {
                    if ((item as UserControl) == null && item.Controls.Count > 0)//如果不是自定义控件
                    {
                        ControlsChange(item);//循环执行
                    }
                    string[] strs = ControlsInfo[item.Name].Split(',');//从字典中查出的数据，以‘，’分割成字符串组

                    for (int i = 0; i < 5; i++)
                    {
                        pos[i] = Convert.ToDouble(strs[i]);//添加到临时数组
                    }
                    double itemWidth = pos[2] * scaleX;     //计算控件宽度，double类型
                    double itemHeight = pos[3] * scaleY;    //计算控件高度
                    item.Left = Convert.ToInt32(pos[0] * scaleX - itemWidth / 2);//计算控件距离左边距离
                    item.Top = Convert.ToInt32(pos[1] * scaleY - itemHeight / 2);//计算控件距离顶部距离
                    item.Width = Convert.ToInt32(itemWidth);//控件宽度，int类型
                    item.Height = Convert.ToInt32(itemHeight);//控件高度
                    item.Font = new Font(item.Font.Name, float.Parse((pos[4] * Math.Min(scaleX, scaleY)).ToString()));//字体
                }
            }
        }
        #endregion
        #endregion

        #region 嵌入窗体

        private void Openpanel(Form childForm, Panel panelwhat)
        {
            //if (!(Mode==0))
            //{
            //    foreach (Control item in panelwhat.Controls)//把容器里已经有的的元素遍历
            //    {
            //        if (item is Form)  //筛选出已经有的窗体
            //        {
            //            ((Form)item).Close();  //把之前存在的窗体删除
            //        }
            //    }
            //    childForm = new Form();
            //}
            panelwhat.Controls.Clear();
            childForm.TopLevel = false; //将子窗体设为非顶级控件
            childForm.FormBorderStyle = FormBorderStyle.None; //将窗体设置为无边框
            childForm.Parent = panelwhat; // 设置窗体的父容器
            childForm.Dock = DockStyle.Fill; //随着容器的大小自动调整窗体大小
            childForm.Show();
        }

        #endregion

        #region 窗体通用按钮
        private void btn_Close_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确认退出吗？", "窗体退出询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                //保存...
                LogicSingle.Instaince.SaveImage();
                ScanConnDevice.Cancel();
                LogicSingle.Instaince._Token_RunningTask.Cancel();//取消运行线程
                System.Environment.Exit(0);//退出所有线程
                this.Close();
                
            }
            

        }
        Form FormNow;// 当前嵌入窗体
        private void btn_FormSize_Click(object sender, EventArgs e)
        {
            panel_Right.Controls.Clear();
            if (((Button)sender).Text == "□")
            {
                this.WindowState = FormWindowState.Maximized;
                ((Button)sender).Text = "▢";
            }
            else
            {
                this.WindowState = FormWindowState.Normal;
                ((Button)sender).Text = "□";
            }
            if (!(FormNow == null))
            {
                Openpanel(FormNow, panel_Right);
            }
        }
        private void btn_MinOrMaxFormClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
        #endregion

        #region 窗体切换
        /// <summary>
        /// 窗体切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_FormUpdata_Click(object sender, EventArgs e)
        {
            switch (((UIButton)sender).Tag.ToString())
            {
                case "1":
                    Openpanel(_OrderForm, panel_Right);
                    FormNow = _OrderForm;
                    break;
                case "2":
                    Openpanel(_ConnTestForm, panel_Right);
                    FormNow = _ConnTestForm;
                    break;
                case "3":
                    Openpanel(_FormConnSet, panel_Right);
                    FormNow = _FormConnSet;
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region 设备状态扫描线程
        /// <summary>
        /// 设备状态扫描线程
        /// </summary>
        public void StateThread()
        {
            Task StateTask = new Task(() =>
                 {
                     while (!ScanConnDevice.IsCancellationRequested)
                     {
                         Thread.Sleep(3000);
                         Invoke(new Action(() =>
                         {                            
                             #region 服务器
                             if (!(LogicSingle.Instaince._UperComputerClientent == null))
                             {
                                 if (LogicSingle.Instaince._UperComputerClientent.IsConnection)
                                 {
                                     if (tLab_ServerStateValue.Text != "已连接")
                                     {
                                         tLab_ServerStateValue.Text = "已连接";
                                         tLab_ServerStateValue.ForeColor = Color.Blue;
                                     }

                                 }
                                 else
                                 {
                                     if (tLab_ServerStateValue.Text != "未连接")
                                     {
                                         tLab_ServerStateValue.Text = "未连接";
                                         tLab_ServerStateValue.ForeColor = Color.Maroon;
                                     }
                                   
                                 }
                             }
                             #endregion

                             #region CCD
                             if (!(LogicSingle.Instaince._CCDClientent == null))
                             {
                                 if (LogicSingle.Instaince._CCDClientent.IsConnection)
                                 {
                                     if (tLab_CCDStateValue.Text != "已连接")
                                     {
                                         tLab_CCDStateValue.Text = "已连接";
                                         tLab_CCDStateValue.ForeColor = Color.Blue;
                                     }
                                   
                                 }
                                 else
                                 {
                                     if (tLab_CCDStateValue.Text != "未连接")
                                     {
                                         tLab_CCDStateValue.Text = "未连接";
                                         tLab_CCDStateValue.ForeColor = Color.Maroon;
                                     }
                                  
                                 }
                             }
                             #endregion

                             #region PLC
                             if (!(LogicSingle.Instaince._PLCDevice == null))
                             {
                                 if (!(LogicSingle.Instaince._PlcConnect == null))
                                 {
                                     if (LogicSingle.Instaince._PlcConnect.IsSuccess)
                                     {
                                         if (tLab_PLCStateValue.Text != "已连接")
                                         {
                                             tLab_PLCStateValue.Text = "已连接";
                                             tLab_PLCStateValue.ForeColor = Color.Blue;
                                         }
                                      
                                     }
                                     else
                                     {
                                         if (tLab_PLCStateValue.Text != "未连接")
                                         {
                                             tLab_PLCStateValue.Text = "未连接";
                                             tLab_PLCStateValue.ForeColor = Color.Maroon;
                                         }
                                     
                                     }
                                 }

                             }
                             #endregion

                             #region 机器人
                             if (!(LogicSingle.Instaince._RobotClient == null))
                             {
                                 if (LogicSingle.Instaince._RobotClient.IsConnection)
                                 {
                                     if (tLab_RobotStateValue.Text != "已连接")
                                     {
                                         tLab_RobotStateValue.Text = "已连接";
                                         tLab_RobotStateValue.ForeColor = Color.Blue;
                                     }
                                    
                                 }
                                 else
                                 {
                                     if (tLab_RobotStateValue.Text != "未连接")
                                     {
                                         tLab_RobotStateValue.Text = "未连接";
                                         tLab_RobotStateValue.ForeColor = Color.Maroon;
                                     }
                            
                                 }
                             }

                             #endregion

                             #region 扫码抢
                             if (!(LogicSingle.Instaince._ScanClient == null))
                             {
                                 if (LogicSingle.Instaince._ScanClient.IsConnection)
                                 {
                                     if (tLab_ScanStateValue.Text != "已连接")
                                     {
                                         tLab_ScanStateValue.Text = "已连接";
                                         tLab_ScanStateValue.ForeColor = Color.Blue;
                                     }
                                
                                 }
                                 else
                                 {
                                     if (tLab_ScanStateValue.Text != "未连接")
                                     {
                                         tLab_ScanStateValue.Text = "未连接";
                                         tLab_ScanStateValue.ForeColor = Color.Maroon;
                                     }
                                 
                                 }
                             }

                             #endregion

                             #region 测高
                             if (!(LogicSingle.Instaince._HeightDevice == null))
                             {
                                 if (LogicSingle.Instaince._HeightDevice.IsOpen)
                                 {
                                     if (tLab_HeightStateValue.Text != "已连接")
                                     {
                                         tLab_HeightStateValue.Text = "已连接";
                                         tLab_HeightStateValue.ForeColor = Color.Blue;
                                     }
                             
                                 }
                                 else
                                 {
                                     if (tLab_HeightStateValue.Text != "未连接")
                                     {
                                         tLab_HeightStateValue.Text = "未连接";
                                         tLab_HeightStateValue.ForeColor = Color.Maroon;
                                     }
                                    
                                 }
                             }

                             #endregion

                             #region 测重

                             if (!(LogicSingle.Instaince._WeightDevice == null))
                             {
                                 if (LogicSingle.Instaince._WeightDevice.IsOpen)
                                 {
                                     if ( tLab_WeightStateValue.Text != "已连接")
                                     {
                                         tLab_WeightStateValue.Text = "已连接";
                                         tLab_WeightStateValue.ForeColor = Color.Blue;
                                     }
                             
                                 }
                                 else
                                 {
                                     if (tLab_WeightStateValue.Text != "未连接")
                                     {
                                         tLab_WeightStateValue.Text = "未连接";
                                         tLab_WeightStateValue.ForeColor = Color.Maroon;
                                     }
                                  
                                 }
                             }
                         }));
                     };

                     #endregion
                 });

            StateTask.Start();
        }
        #endregion

        #region 日志添加
        /// <summary>
        /// 日志添加
        /// </summary>
        /// <param name="log"></param>
        public void AddLog(string log)
        {
            if (lView_MainLog.InvokeRequired)
            {
                Invoke(new Action(() =>
                {
                    ListViewItem listviewitem = new ListViewItem(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    listviewitem.SubItems.Add(log);
                    lView_MainLog.Items.Insert(0, listviewitem);
                }));
            }
            else
            {
                ListViewItem listviewitem = new ListViewItem(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                listviewitem.SubItems.Add(log);
                lView_MainLog.Items.Insert(0, listviewitem);
            }


        }
        #endregion

        /// <summary>
        /// 订单状态
        /// </summary>
        /// <param name="State"></param>
        public void OrderState(int State)
        {
            //Color.Maroon;
            Invoke(new Action(() =>
            {
                switch (State)
                {
                    case 0:
                        lab_OrderState.Text = "无异常";
                        pan_OrderStateBack.BackColor = SystemColors.Highlight;
                        break;
                    case 1:
                        lab_OrderState.Text = "开工异常";
                        pan_OrderStateBack.BackColor = Color.Maroon;
                        break;
                    case 2:
                        lab_OrderState.Text = "报工异常";
                        pan_OrderStateBack.BackColor = Color.Maroon;
                        break;
                    default:
                        break;
                }
            }));
        }

        /// <summary>
        /// 上位机程序状态选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comB_ProgramMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comB_ProgramMode.Text == "自动")
            {
                LogicSingle.Instaince.RuningState = true;
            }
            else
            {
                LogicSingle.Instaince.RuningState = false;
            }
        }
    }
}
